package com.parsechina.hpush.broker.spi.persistence;

import com.parsechina.hpush.broker.internal.MessageGUID;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author linfeng
 * @since 2016/12/21
 */
public final class SessionsStoreUtils {

    private static ConcurrentMap<String, ConcurrentMap<Integer, MessageGUID>> clientMessageIdToGuid = new ConcurrentHashMap<>();

    private SessionsStoreUtils() {
    }

    public static String messageId2GuidsMapName(String clientId) {
        return "guidsMapping_" + clientId;
    }

    public static void putMessageToGuid(String clientId, Integer messageId, MessageGUID guid) {
        ConcurrentMap<Integer, MessageGUID> messageToGuid = clientMessageIdToGuid.get(messageId2GuidsMapName(clientId));
        if (messageToGuid == null) {
            messageToGuid = new ConcurrentHashMap<>();
        }
        messageToGuid.put(messageId, guid);
        clientMessageIdToGuid.put(messageId2GuidsMapName(clientId), messageToGuid);
    }

    public static ConcurrentMap<Integer, MessageGUID> getMessageToGuid(String clientId) {
        return clientMessageIdToGuid.get(messageId2GuidsMapName(clientId));
    }

    public static void removeMessageToGuid(String clientId, Integer messageId) {
        ConcurrentMap<Integer, MessageGUID> messageToGuid = clientMessageIdToGuid.get(messageId2GuidsMapName(clientId));
        if (messageToGuid == null) {
            messageToGuid = new ConcurrentHashMap<>();
        } else {
            messageToGuid.remove(messageId);
        }
        clientMessageIdToGuid.put(messageId2GuidsMapName(clientId), messageToGuid);
    }

}
